<?php
/**
 * Controller is the customized base controller class.
 * All controller classes for this application should extend from this base class.
 */
class DirController extends Controller
{

	protected $getParams=array();
	
	public $dirname;
	
	public $model;
	
	public $layout='column2_dir';	
	

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=CActiveRecord::model($this->model)->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}
	
	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('@','admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}
	
	
	/**
	 * This method is invoked right before an action is to be executed (after all possible filters.)
	 * You may override this method to do last-minute preparation for the action.
	 * @param CAction $action the action to be executed.
	 * @return boolean whether the action should be executed.
	 */
	protected function beforeAction($action)
	{
		switch ($action->id){
			case 'create': $actionId='Добавить';
			case 'index': $actionId='Список';
			default: $actionId=$action->id;
		}
		
		$this->breadcrumbs=array(
			$this->dirname=>array('admin'),
			$actionId,
		);

		$this->menu=array(
	//		array('label'=>'Администрирование', 'url'=>array('admin')),
			array('label'=>'Добавить', 'url'=>array('create'), 'visible'=>$action->id!='create'),
		);		
		return true;
	}	
	
	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}


	public function renderHeader($action, $model)
	{
		return CHtml::tag('h1',array(),$this->dirname);
	}
	
	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new $this->model;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST[$this->model]))
		{
			$model->attributes=$_POST[$this->model];
			if($model->save())
				if (Yii::app()->request->isAjaxRequest)
					$this->redirect(array_merge(array('admin'),$this->getParams));
				else
					$this->redirect(array_merge(array('admin'),$this->getParams));
		}
		$this->fillAttributes($model);
		
		if(($viewFile=$this->getViewFile('create'))!==false)
		{
			if (Yii::app()->request->isAjaxRequest)
				$this->renderPartial('create',array('model'=>$model),false,true);
			else
				$this->render('create',array('model'=>$model));
		}
		else
		{
			if (Yii::app()->request->isAjaxRequest)
				echo $this->renderActionCreate($model);
			else
				$this->renderText($this->renderActionCreate($model),false);
		}	
	}

	public function renderActionCreate($model)
	{
		$output=$this->renderHeader('create',$model);
		$output.=$this->widget('CMyActiveForm', array(
			'model'=>$model,
		),true);
		return $output;
	} 
	
	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate()
	{
		if (isset($_GET['id']))
			$model=$this->loadModel($_GET['id']);
		else
			throw new CHttpException(400,Yii::t('yii','Your request is invalid.'));

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
			
		if(isset($_POST[$this->model]))
		{
			$model->attributes=$_POST[$this->model];
			if (!Yii::app()->request->isAjaxRequest)
				if($model->save())
					$this->redirect(array_merge(array('admin'),$this->getParams));
		}
		if(($viewFile=$this->getViewFile('update'))!==false)
			$this->render('update',array('model'=>$model));
		else
			$this->renderText($this->renderActionUpdate($model),false);
	}

	public function renderActionUpdate($model)
	{
		$output=$this->renderHeader('update', $model);
		$output.=$this->widget('CMyActiveForm', array(
			'model'=>$model,
		),true);
		return $output;
	} 
	
	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'index' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete()
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			if (isset($_GET['id']))
				$model=$this->loadModel($_GET['id']);
			else
				throw new CHttpException(400,Yii::t('yii','Your request is invalid.'));
			$model->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	
	public function fillAttributes($model)
	{		
		if(isset($_GET[$this->model]))
		{
			$model->attributes=$_GET[$this->model];
			if ($model->saveFilter)
				$_SESSION[$this->model]=$_GET[$this->model];
		}
		else
		{
			if(isset($_SESSION[$this->model]))
			{				
				if ($model->saveFilter)
					$model->attributes=$_SESSION[$this->model];
			}
		}
	}
	
	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{

		$model=new $this->model('search');
		$model->unsetAttributes();  // clear any default values
		$this->fillAttributes($model);
		$this->render('index',array(
			'dataProvider'=>$model->search(),
			'model'=>$model,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new $this->model('search');
		$model->unsetAttributes();  // clear any default values
		$this->fillAttributes($model);
		if(($viewFile=$this->getViewFile('admin'))!==false)
			$this->render('admin',array('model'=>$model));
		else
			$this->renderText($this->renderActionAdmin($model),false);
	}

	public function renderActionAdmin($model)
	{
		$output=$this->renderHeader('admin',$model);
		if ($model->viewColumns===array())
			$columns=array_keys($model->attributes);											
		else
			$columns=$model->viewColumns;
		$columns[]=array(
			'class'=>'CButtonColumn',
			'updateButtonUrl'=>'Yii::app()->controller->createUrl("update",array_merge(Yii::app()->controller->getParams,array("id"=>$data->primaryKey)))',
		);
		$output.=$this->widget('CMyGridView', array(
			'id'=>strtolower($this->model.'-grid'),
			'dataProvider'=>$model->search(),
			'groupName'=>$model->groupName,
			'columns'=>$columns,
		),true);
		return $output;	
	}
	
	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']===$this->model.'-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}    	
}